import React, { useState, useMemo, useCallback, useEffect } from 'react';
import { Modal } from 'antd-mobile';

const ok = (property, obj) => {
    if (obj.loading) return;
    if (obj.setDisabled === undefined) {
        obj.setDisabled = (disabled) => { obj.loading = disabled; };
        obj.setLoading = (loading) => { obj.loading = loading; };
    }

    if (property.onOk) property.onOk({}, obj);
};

const cancel = (property, setIsVisible) => {
    setIsVisible(false);
    if (property.onCancel) property.onCancel();
};

const renderComponent = (property) => {
    const { component, style } = property;

    if (style) return <div style={style}>{component}</div>;
    else return component;
};

export default React.memo((props) => {
    const { property, dispose } = props;
    const [visible, setIsVisible] = useState(property.visible);

    const obj = useMemo(() => ({}), []);

    const onAction = useCallback((a) => {
        if (a.key === 'ok') ok(property, obj);
        else setTimeout(() => cancel(property, setIsVisible), 100);
    }, [property, obj, setIsVisible]);

    useEffect(() => {
        if (property.isDispose && !visible) dispose(property.id);
        if (property.onClosed && !visible) property.onClosed();
    }, [property, dispose, visible]);

    property.setIsVisible = (v) => { property.isVisible = v; setIsVisible(v); };

    if (property.isDispose && !visible) return null;

    const { isOk, title, bodyStyle } = property;

    const actions = [{ key: 'cancel', text: '取消' }];
    if (isOk) actions.push({ key: 'ok', text: '确定', primary: true });

    return <div className='divDialog'><Modal visible={visible}
        content={renderComponent(property)}
        title={title}
        bodyStyle={bodyStyle}
        onAction={onAction}
        actions={actions} /></div>;
});